import React from 'react';
import { Upload, message, Button, Icon } from 'antd';
import 'components/DBTable/index.less';
import globalConfig from 'config.js';
import ajax from '../../../utils/ajax';

//上传音频
function beforeUpload(file) {
  console.log(file.type);
  let isAudio=false;
  const audioType=[
     'audio/mp3',
     'audio/x-ms-wma',
     'audio/wav',
     'audio/mpeg'
  ];

  for(let i=0;i<audioType.length;i++){
    if(audioType[i]==file.type){
      isAudio=true;
    }
  }
  if (!isAudio) {
    message.error('只能上传音频文件');
  }
  //const isLt2M = file.size / 1024 / 1024 < 2;
  //if (!isLt2M) {
    //message.error('Image must smaller than 2MB!');
  //}
  //return isJPG && isLt2M;
  return isAudio;
}

class UploadAudio extends React.Component {

  state = {
    defaultFileObj: []
  }

  componentWillMount = () => {
    this.initDefaultFile(this.props);
  }

  componentWillReceiveProps = (nextProps) => {
    this.initDefaultFile(nextProps);
  }

  initDefaultFile = (props) => {
    let defaultFileObj = [];
    let defaultFileItemPropsItem = props.defaultFileList;
    console.log(defaultFileItemPropsItem);

    if (defaultFileItemPropsItem) { //处理已上传的音频
      let defaultFileItem = {};
      defaultFileItem.uid = defaultFileItemPropsItem.id;
      defaultFileItem.name = "已上传的音频";
      defaultFileItem.status = "done";

      if (defaultFileItemPropsItem.voiceUrl) {
        defaultFileItem.url = defaultFileItemPropsItem.voiceUrl;
      }
      else{
        defaultFileItem.url = defaultFileItemPropsItem.url;
      }

      defaultFileObj.push(defaultFileItem);
      this.setState({ defaultFileObj: defaultFileObj });
    }
    else {
      this.setState({ defaultFileObj: [] });
    }
  }

  handleUpChange = (info) => {

    let fileList = info.fileList;

    if (fileList.length > 1) {
      fileList = fileList.slice(-1); //最多只能有一个音频

      fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.data.url;
        }
        return file;
      });

      this.setState({ defaultFileObj: fileList });

      if (info.file.response) {
        this.props.uploadVideo(info.file.response.data.key);
      }
    }
    else {
      this.setState({ defaultFileObj: fileList });
      if (info.file.response) {
        this.props.uploadVideo(info.file.response.data);
      }
    }



  }

  handleRemove = () => {
    this.setState({ defaultFileObj: [] });
  }

  render() {
    return (
      <div>
        <Upload action="/image/upload"
          onChange={this.handleUpChange}
          onRemove={this.handleRemove}
          beforeUpload={beforeUpload}
          fileList={this.state.defaultFileObj}>
          <Button type="ghost">
            <Icon type="upload" />上传音频
          </Button>
        </Upload>
      </div>
    );
  }

}

export default UploadAudio;
